﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using General.Entities.Data;
using General.Entities.Models;
using General.Entities.ViewData.SystemConfig;
using General.Framework;
using General.Framework.Admin;
using General.Mvc.Filters;
using General.Mvc.Jobs;
using General.Services.Admin;
using General.Services.Dictionary;
using General.Services.DicType;
using General.Services.Note;
using General.Services.Region;
using General.Services.Role;
using General.Services.SystemConfig;
using General.Services.SystemLogs;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Quartz;

namespace General.Mvc.Controllers
{
    [Route("api/admin/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class AdminApiController : Controller
    {
        private readonly IAdminService adminService;
        private readonly INoteService noteService;
        private readonly ISystemLogsService systemLogsService;
        private readonly IRoleService roleService;
        private readonly IDicTypeService dicTypeService;
        private readonly IDictionaryService dictionaryService;
        private readonly IRegionService regionService;
        private readonly ISystemConfigService systemConfigService;
        private readonly ILogger<AdminApiController> logger;
        private readonly ISchedulerFactory schedulerFactory;
        private IScheduler _scheduler;
        private readonly IMapper mapper;

        public AdminApiController(IAdminService adminService, INoteService noteService,
            ISystemLogsService systemLogsService,
            IRoleService roleService,
            IDicTypeService dicTypeService,
             IDictionaryService dictionaryService,
             IRegionService regionService,
             ISystemConfigService systemConfigService,
            ILogger<AdminApiController> logger,
            ISchedulerFactory schedulerFactory,
            IMapper mapper)
        {
            this.adminService = adminService;
            this.noteService = noteService;
            this.systemLogsService = systemLogsService;
            this.roleService = roleService;
            this.dicTypeService = dicTypeService;
            this.dictionaryService = dictionaryService;
            this.regionService = regionService;
            this.systemConfigService = systemConfigService;
            this.logger = logger;
            this.schedulerFactory = schedulerFactory;
            this.mapper = mapper;
        }


        /// <summary>
        /// 管理登录处理方法
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <param name="CaptchaCode"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> LoginProcess([FromForm]string UserName,[FromForm]string Password,[FromForm]string CaptchaCode)
        {
            AjaxResult result = new AjaxResult();
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password))
            {
                result.code =  AjaxResultStateEnum.Error;
                result.message = "账号或密码不能为空！";
                return Content(JsonHelper.Serialize(result));
            }
            var SysCode = HttpContext.Session.GetString("CaptchaCode");
            if (string.IsNullOrEmpty(CaptchaCode) || CaptchaCode.Trim() != SysCode)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "验证码错误！";
                return Content(JsonHelper.Serialize(result));
            }

            var user = await adminService.GetInfoByUserName(UserName);
            if (user == null)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "不存在此账户！";
                return Content(JsonHelper.Serialize(result));
            }
            var ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Connection.RemoteIpAddress.ToString();
            }

            if (user.password != EncryptHelper.Md5(Password))
            {
                logger.LogInformation(new Exception("登录失败"), "ip:" + ip + " 用户名:" + UserName + " 密码:" + Password);
                result.code = AjaxResultStateEnum.Error;
                result.message = "密码错误！";
                return Content(JsonHelper.Serialize(result));
            }
            if (user.status != 1)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "您被禁止登录！";
                return Content(JsonHelper.Serialize(result));
            }
            logger.LogInformation(new Exception("登录成功"), "ip:" + ip + " 用户名:" + UserName + " 密码:" + Password);
            //更新最后登录信息
            await adminService.UpdateLoginStatusInfo(user.id,ip);

            //存入Session
            HttpContext.Session.SetString("Admin",JsonHelper.Serialize(user));

            result.code = AjaxResultStateEnum.Ok;
            result.message = "登录成功！";
            return Content(JsonHelper.Serialize(result));
        }



        #region 管理员列表
        /// <summary>
        /// 获取管理员列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetAdminList(int page, int limit, string username,int status=-1)
        {
            var list = await adminService.GetList(page, limit, username,status);
            return Content(JsonHelper.Serialize(list));
        }

        /// <summary>
        /// 增加管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddAdminInfo([FromForm]string username,[FromForm]int status,[FromForm]string role)
        {
            var result = new AjaxResult();
            if (string.IsNullOrWhiteSpace(username))
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "账号不能为空！";
                return Content(JsonHelper.Serialize(result));
            }
            var isExist = await adminService.GetInfoByUserName(username);
            if (isExist != null)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "此用户名已存在！";
                return Content(JsonHelper.Serialize(result));
            }
            var res = await adminService.AddInfo(username,status,role);
            if (res>0)
            {
                result.code = AjaxResultStateEnum.Ok;
                result.message = "添加成功！";
                return Content(JsonHelper.Serialize(result));
            }
            else
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "发生错误！";
                return Content(JsonHelper.Serialize(result));
            }
            
        }
        
        /// <summary>
        /// 编辑管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditAdminInfo([FromForm]tc_admin data)
        {
            var result = new AjaxResult();
            if (string.IsNullOrWhiteSpace(data.username))
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "账号不能为空！";
                return Content(JsonHelper.Serialize(result));
            }
            var isExist = await adminService.GetInfoByUserName(data.username);
            if (isExist !=null && isExist.id !=data.id)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "此用户名已存在！";
                return Content(JsonHelper.Serialize(result));
            }
            await adminService.EditInfo(data);
            result.code = AjaxResultStateEnum.Ok;
            result.message = "编辑成功！";
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteAdminInfo([FromForm]string ids)
        {
            var res = await adminService.DeleteInfo(ids);
            if (res > 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功！" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误！" }));
            }
        }

        /// <summary>
        /// 修改管理员状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditAdminStatus([FromForm]int id,[FromForm]int status)
        {
            var res = await adminService.EditStatus(id,status);
            if (res > 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "修改成功！" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误！" }));
            }
        }


        /// <summary>
        /// 修改管理员密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> UpdateAdminPassword([FromForm]int uid,[FromForm]string password)
        {
            await adminService.UpdateUserPwd(uid,password);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "修改成功！" }));
        }

        #endregion


        #region 系统设置
        /// <summary>
        /// 添加系统配置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddSystemConfig([FromForm]tc_sysconfig sysconfig)
        {
            AjaxResult result = new AjaxResult();
            var isExist = await systemConfigService.GetConfigInfoByCode(sysconfig.code);
            if (isExist!=null)
            {
                return Content(result.Error("添加失败！已存在此配置标识！"));
            }
            var res = await systemConfigService.AddConfigData(sysconfig);
            if (res>0)
            {
                return Content(result.Ok("添加成功"));
            }
            return Content(result.Error("添加失败"));
        }

        /// <summary>
        /// 编辑系统配置信息
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditSystemConfig([FromForm]int tid,[FromForm]string data)
        {
            AjaxResult result = new AjaxResult();
            var list = JsonHelper.Deserialize<List<SystemConfigModel>>(data);
            await systemConfigService.EditConfigData(tid, list);
            return Content(result.Ok("设置成功"));
        }

        #endregion


        #region 便签接口
        /// <summary>
        /// 获取所有本地便签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> GetNoteList()
        {
            var res = await noteService.GetAllList();
            var list = mapper.Map<List<AdminNoteModel>>(res);
            return Content(JsonHelper.Serialize(list));
        }

        /// <summary>
        /// 添加便签
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddNote([FromForm]string message)
        {
            var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
            await noteService.AddInfo(message,user.id);
            return Content(JsonHelper.Serialize(new AjaxResult() { code= AjaxResultStateEnum.Ok, message="添加成功!" }));
        }

        /// <summary>
        /// 编辑便签
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditNote([FromForm] string message,[FromForm]int id)
        {
            await noteService.UpdateInfo(id,message);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "编辑成功!" }));
        }

        /// <summary>
        /// 删除便签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteNote([FromForm] int id)
        {
            await noteService.DeleteInfo(id);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功!" }));
        }
        #endregion

        #region 系统日志
        /// <summary>
        /// 获取系统日志列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetSystemLog(int page,int limit,string message,string exception,string level)
        {
            var list = await systemLogsService.GetList(page,limit,message,exception,level);
            return Content(JsonHelper.Serialize(list));
        }
        /// <summary>
        /// 清空系统日志列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteAllSystemLog()
        {
            var res = await systemLogsService.DeleteAll();
            if (res>0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message="清空成功！" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "已清空，无须再次清空！" }));
            }
        }

        /// <summary>
        /// 删除系统日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteSystemLogByIds([FromForm]string ids)
        {
            await systemLogsService.DeleteByIds(ids);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功！" }));
        }

        #endregion



        #region 角色管理
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetAllRole()
        {
            var list = await roleService.GetAllList();
            return Content(JsonHelper.Serialize(list));
        }
        /// <summary>
        /// 查询角色列表
        /// </summary>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetRoleList(int page, int limit, string rolename, string rolecode, string remark)
        {
            var list = await roleService.GetList(page,limit,rolename,rolecode,remark);
            return Content(JsonHelper.Serialize(list));
        }
        /// <summary>
        /// 增加角色信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddRoleInfo([FromForm]tc_role role)
        {
            await roleService.AddInfo(role);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message="添加成功" }));
        }
        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditRoleInfo([FromForm] tc_role role)
        {
            await roleService.EditInfo(role.id,role);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "修改成功" }));
        }
        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteRoleInfo([FromForm] string ids)
        {
            var res = await roleService.DeleteInfo(ids);
            if (res>0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误" }));
            }
        }
        #endregion


        #region 字典管理
        /// <summary>
        /// 查询字典类型列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetDicTypeList(int page,int limit,string name)
        {
            var list = await dicTypeService.GetList(page,limit,name);
            return Content(JsonHelper.Serialize(list));
        }
        /// <summary>
        /// 增加字典类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddDicType([FromForm]tc_dictype dictype)
        {
            await dicTypeService.AddInfo(dictype);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message="增加成功!" }));
        }
        /// <summary>
        /// 编辑字典类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditDicType([FromForm] tc_dictype dictype)
        {
            await dicTypeService.EditInfo(dictype);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "编辑成功!" }));
        }
        /// <summary>
        /// 删除字典类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteDicType([FromForm] string ids)
        {
            var res=await dicTypeService.DeleteInfo(ids);
            if (res > 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误" }));
            }
        }
        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetDictionaryList(int page, int limit, int typeid, string? dicname, string? dicode)
        {
            var list = await dictionaryService.GetList(page,limit,typeid, dicname,dicode);
            return Content(JsonHelper.Serialize(list));
        }
        /// <summary>
        /// 增加字典数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddDictInfo([FromForm] tc_dictionary dictionary)
        {
            var res = await dictionaryService.AddInfo(dictionary);
            if (res == 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "已存在字典项名称!" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "增加成功!" }));
            }
        }
        /// <summary>
        /// 编辑字典数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditDictInfo([FromForm] tc_dictionary dictionary)
        {
            await dictionaryService.EditInfo(dictionary);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "编辑成功!" }));
        }
        /// <summary>
        /// 删除字典数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteDictInfo([FromForm] string ids)
        {
            var res = await dictionaryService.DeleteInfo(ids);
            if (res > 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误" }));
            }
        }
        #endregion


        #region 区域管理
        /// <summary>
        /// 获取区域列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetRegionList(int page,int limit,string name,int level)
        {
            var list = await regionService.GetList(page,limit,name,level);
            return Content(JsonHelper.Serialize(list));
        }
        /// <summary>
        /// 增加区域信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddRegionInfo([FromForm] tc_region data)
        {
            await regionService.AddInfo(data);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "添加成功" }));
        }
        /// <summary>
        /// 修改区域信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditRegionInfo([FromForm] tc_region data)
        {
            await regionService.EditInfo(data);
            return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "修改成功" }));
        }
        /// <summary>
        /// 删除区域信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteRegionInfo([FromForm] string ids)
        {
            var res = await regionService.DeleteInfo(ids);
            if (res > 0)
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Ok, message = "删除成功" }));
            }
            else
            {
                return Content(JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Fail, message = "出现错误" }));
            }
        }
        #endregion

        #region 定时任务
        /// <summary>
        /// 获取定时任务列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public async Task<IActionResult> GetJobList(int page, int limit, string name, string remark)
        {
            AdminResult result = new AdminResult();
            var list = JobListModel.list.OrderByDescending(x=>x.id).ToList();
            result.count = list.Count;
            if (!string.IsNullOrWhiteSpace(name))
            {
                list = list.Where(x => x.name.Contains(name)).ToList();
            }
            if (!string.IsNullOrWhiteSpace(remark))
            {
                list = list.Where(x => x.remark.Contains(remark)).ToList();
            }
            result.data = list.Skip((page - 1) * limit).Take(limit).ToList();
            result.code = 0;
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 添加定时任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> AddJobInfo([FromForm]JobItemModel job,[FromForm]int jobType, [FromForm]string url)
        {
            AjaxResult result = new AjaxResult();
            var isExist = JobListModel.list.Where(x => x.name == job.name).FirstOrDefault();
            if (isExist!=null)
            {
                return Content(result.Error("添加失败！已存在相同名称任务！"));
            }
            if (jobType == 1) //访问url
            {
                _scheduler = await schedulerFactory.GetScheduler();
                await _scheduler.Start();
                var trigger = TriggerBuilder.Create()
                                .WithCronSchedule(job.trigger)
                                .Build();
                var jobDetail = JobBuilder.Create<RequestUrlJob>()
                                .WithIdentity(job.name, "group")
                                .UsingJobData("url", url)
                                .Build();
                await _scheduler.ScheduleJob(jobDetail, trigger);
            }
            else if (jobType == 2) //清空日志
            {
                _scheduler = await schedulerFactory.GetScheduler();
                await _scheduler.Start();
                var trigger = TriggerBuilder.Create()
                                .WithCronSchedule(job.trigger)
                                .Build();
                var jobDetail = JobBuilder.Create<ClearSystemLogsJob>()
                                .WithIdentity(job.name, "group")
                                .Build();
                await _scheduler.ScheduleJob(jobDetail, trigger);
            }
            else
            {
                return Content(result.Error("任务类型错误！"));
            }
            JobListModel.list.Add(new JobItemModel() { id = JobListModel.Increment, createtime=DateTime.Now, name = job.name, remark = job.remark, trigger = job.trigger });
            JobListModel.Increment = JobListModel.Increment + 1;
            return Content(result.Ok("添加成功"));
        }

        /// <summary>
        /// 删除定时任务
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> DeleteJobInfo([FromForm]string ids)
        {
            AjaxResult result = new AjaxResult();
            var arr = ids.Split(",",StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x));
            foreach (var item in arr)
            {
                var temp = JobListModel.list.Where(x => x.id == item).FirstOrDefault();
                _scheduler = await schedulerFactory.GetScheduler();
                TriggerKey triggerKey = new TriggerKey(temp.name, "group");
                await _scheduler.PauseTrigger(triggerKey);//停止触发器
                await _scheduler.UnscheduleJob(triggerKey);//移除触发器
                await _scheduler.DeleteJob(new JobKey(temp.name, "group"));//删除任务
                JobListModel.list.Remove(temp);
            }
            return Content(result.Ok("删除成功"));
        }

        #endregion

        /// <summary>
        /// 修改我的用户名
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditMyUserName([FromForm]string name)
        {
            AjaxResult result = new AjaxResult();
            if (string.IsNullOrWhiteSpace(name))
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "用户名不能为空！";
                return Content(JsonHelper.Serialize(result));
            }
            var isExist = await adminService.GetInfoByUserName(name);
            if (isExist!=null)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "此用户名已存在！";
                return Content(JsonHelper.Serialize(result));
            }
            var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
            await adminService.UpdateUsername(user,name);
            result.code = AjaxResultStateEnum.Ok;
            result.message = "修改成功！";
            return Content(JsonHelper.Serialize(result));
        }


        /// <summary>
        /// 修改我的登录密码
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> EditMyPassWord([FromForm]string oldPsw,[FromForm]string newPsw)
        {
            AjaxResult result = new AjaxResult();
            var session = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
            var user = await adminService.GetInfoById(session.id);
            if (EncryptHelper.Md5(oldPsw) != user.password)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "修改失败！原密码错误！";
                return Content(JsonHelper.Serialize(result));
            }
            if (string.IsNullOrWhiteSpace(newPsw) || newPsw.Length < 6 || newPsw.Length > 16)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "修改失败！请检查新密码长度！";
                return Content(JsonHelper.Serialize(result));
            }
            await adminService.UpdateUserPwd(user.id,newPsw);

            result.code = AjaxResultStateEnum.Ok;
            result.message = "修改成功！";
            return Content(JsonHelper.Serialize(result));
        }


        #region 文件管理

        /// <summary>
        /// 上传Base64图片
        /// </summary>
        /// <param name="fileBase64"></param>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> UploadBase64([FromServices] IWebHostEnvironment environment, [FromForm] string fileBase64)
        {
            AjaxResult result = new AjaxResult();
            string path = string.Empty;
            byte[] bytes = Convert.FromBase64String(fileBase64);
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            string newFileName = System.Guid.NewGuid().ToString() + ".png"; //随机生成新的文件名
            var filePath = webRootPath + "/upload/" + timedir;
            var RetfilePath = "upload/" + timedir + newFileName;
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = webRootPath + "/upload/" + timedir + newFileName;
            try
            {
                result.code = AjaxResultStateEnum.Ok;
                FileStream fs = new FileStream(filePath, FileMode.CreateNew);
                await fs.WriteAsync(bytes, 0, bytes.Length);
                fs.Close();
                result.message = "/" + RetfilePath;
                var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
                await adminService.UpdateHeadImg(user.id, result.message);
            }
            catch (Exception ex)
            {
                result.code = AjaxResultStateEnum.Error;
                result.message = "上传失败!";
                logger.LogInformation(new Exception("UploadBase64上传失败"), ex.Message);
            }
            return Content(JsonHelper.Serialize(result));
        }



        /// <summary>
        /// 文件管理接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AdminCheckFilter]
        public IActionResult Getfile([FromServices] IWebHostEnvironment environment, string dir)
        {
            List<AppLocalFileModel> list = new List<AppLocalFileModel>();
            DirectoryInfo localdir = new DirectoryInfo(environment.WebRootPath + "/upload" + dir);

            DirectoryInfo[] dii = localdir.GetDirectories();
            foreach (var item in dii)
            {
                AppLocalFileModel temp = new AppLocalFileModel()
                {
                    hasSm = false,
                    isDir = true,
                    name = item.Name,
                    smUrl = "",
                    type = "dir",
                    url = ""
                };
                list.Add(temp);
            }
            FileInfo[] fil = localdir.GetFiles();
            foreach (var item in fil)
            {
                var isimg = false;
                var fileExt = item.Extension.ToLower();
                if (fileExt.Contains("jpg") || fileExt.Contains("png") || fileExt.Contains("jepg") || fileExt.Contains("gif"))
                {
                    isimg = true;
                }

                AppLocalFileModel temp = new AppLocalFileModel()
                {
                    hasSm = isimg,
                    isDir = false,
                    name = item.Name,
                    smUrl = isimg ? "/image/getpath?name=" + (dir == "/" ? "/" : dir + "/") + item.Name : "",
                    type = "file",
                    url = "/upload" + (dir == "/" ? "/" : dir + "/") + item.Name
                };
                list.Add(temp);
            }

            return Content(JsonHelper.Serialize(new { code = 200, data = list, mes = "sucess" }));
        }

        /// <summary>
        /// 删除文件接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public IActionResult DeleteFile([FromServices] IWebHostEnvironment environment, [FromForm] string name)
        {
            AjaxResult result = new AjaxResult();
            name = name.Replace("/upload", "");
            string webRootPath = environment.WebRootPath;
            if (System.IO.File.Exists(webRootPath + "/upload" + name))
            {
                System.IO.File.Delete(webRootPath + "/upload" + name);
                result.code = AjaxResultStateEnum.Ok;
                result.message = "删除成功!";
            }
            else
            {
                result.code = AjaxResultStateEnum.Fail;
                result.message = "不存在此文件!";
            }
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 创建文件夹接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        public async Task<IActionResult> CreateFolder([FromServices] IWebHostEnvironment environment, [FromForm] string name, [FromForm] string dir = "/")
        {
            AjaxResult result = new AjaxResult();
            string webRootPath = environment.WebRootPath;
            dir = (dir == "/" ? "/" : dir + "/") + name;
            if (!Directory.Exists(webRootPath + "/upload" + dir))
            {
                Directory.CreateDirectory(webRootPath + "/upload" + dir);
                result.code = AjaxResultStateEnum.Ok;
                result.message = "创建成功";
            }
            else
            {
                result.code = AjaxResultStateEnum.Fail;
                result.message = "已存在同名文件夹!";
            }

            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 弹窗选择文件上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        [RequestSizeLimit(5000_000_000)] //最大5000m
        public async Task<IActionResult> UploadFile2([FromServices] IWebHostEnvironment environment,string resultType)
        {
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { return Json(new { code = 0, msg = "请选择上传的文件." }); }
            string webRootPath = environment.WebRootPath;
            var Month = DateTime.Now.Month.ToString();
            var Day = DateTime.Now.Day.ToString();
            string timedir = "/" + DateTime.Now.Year + "/" + (Month.Length == 1 ? "0" + Month : Month) + "/" + (Day.Length == 1 ? "0" + Day : Day) + "/";
            if (!Directory.Exists(webRootPath + "/upload" + timedir))
            {
                Directory.CreateDirectory(webRootPath + "/upload" + timedir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload" + timedir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }

            string strpath = Path.Combine("upload" + timedir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }

            if (resultType == "tinymce")
            {
                return Json(new { location = "/" + strpath });
            }

            return Json(new { code = 200, msg = "上传成功!" });
        }

        /// <summary>
        /// 文件上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminCheckFilter]
        [RequestSizeLimit(5000_000_000)] //最大5000m
        public async Task<IActionResult> UploadFile([FromServices] IWebHostEnvironment environment, [FromForm] string dir = "/")
        {
            AjaxResult state = new AjaxResult();
            string path = string.Empty;
            var files = Request.Form.Files.Where(c => c.Name == "file");
            if (files == null || files.Count() <= 0) { state.code = 0; state.message = "请选择上传的文件。"; return Json(state); }
            string webRootPath = environment.WebRootPath;

            if (!Directory.Exists(webRootPath + "/upload" + dir))
            {
                Directory.CreateDirectory(webRootPath + "/upload" + dir);
            }
            var filename = files.FirstOrDefault().FileName;
            if (System.IO.File.Exists(webRootPath + "/upload" + dir + filename))
            {
                var guid = Guid.NewGuid();
                filename = guid + Path.GetExtension(files.FirstOrDefault().FileName);
            }

            string strpath = Path.Combine("upload" + dir, filename);

            path = Path.Combine(webRootPath, strpath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                await files.FirstOrDefault().CopyToAsync(stream);
            }


            state.code = AjaxResultStateEnum.Ok;
            state.message = "上传成功";
            return Json(state);
        }

        #endregion

    }
}
